package setup

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"my-gin-tiktok/global"
	"os"
)

func InitConfig() *viper.Viper {
	config := "config.yaml"
	if configFile := os.Getenv("CONFIG_FILE"); configFile != "" {
		config = configFile
	}

	// 读取配置
	v := viper.New()
	v.SetConfigFile(config)
	v.SetConfigType("yaml")
	if err := v.ReadInConfig(); err != nil {
		panic("ReadInConfig Failed:" + err.Error())
	}

	// 监听配置
	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
		if err := v.Unmarshal(&global.App.Config); err != nil {
			panic("ConfigChange ==> Unmarshal Config Failed:" + err.Error())
		}
	})

	if err := v.Unmarshal(&global.App.Config); err != nil {
		panic("First Unmarshal Config Failed:" + err.Error())
	}
	return v
}
